//
//  DDFavouriteViewController.m
//  Dingdong
//
//  Created by 程强 on 16/11/11.
//  Copyright © 2016年 程强. All rights reserved.
//

#import "DDFavouriteViewController.h"
#import "DDFavouriteCollectionCell.h"
#import "DDUserManager.h"
#import "DDFavouriteSet.h"
#import "MJRefresh.h"
#import "DDGoodsDetailsViewController.h"
#import "UIAlertView+Click.h"

@interface DDFavouriteViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *favouriteCollection;
@property (strong, nonatomic) DDUserManager *manager;
@property (assign, nonatomic) NSInteger currentPage;
@property (strong, nonatomic) DDFavouriteSet *favouriteSet;
@end

@implementation DDFavouriteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [DDUserManager new];
    [self layoutFavouriteView];
}
- (void)setRefresh
{
    weak_Self(self);
    MJRefreshHeader *header =[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf headerRefresh];
    }];
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf footerRefresh];
    }];
    [self.favouriteCollection setMj_header:header];
    [self.favouriteCollection setMj_footer:footer];
    [self headerRefresh];
}
- (void)headerRefresh
{
    weak_Self(self);
    [self fetchCollectionData:YES complete:^{
        [weakSelf.favouriteCollection.mj_header endRefreshing];
    }];
}
- (void)footerRefresh
{
    weak_Self(self);
    [self fetchCollectionData:NO complete:^{
        [weakSelf.favouriteCollection.mj_footer endRefreshing];
    }];
}
- (void)layoutFavouriteView
{
    [self setRefresh];
}
#pragma mark --- 接口
- (void)fetchCollectionData:(BOOL)pull complete:(void(^)())block
{
    if (pull) {
        self.currentPage = 1;
    }
    weak_Self(self);
    [self showHUD];
    [[self.manager myCollectionWithPageNumber:self.currentPage pageSize:kPageSize]subscribeNext:^(id x) {
        if (pull) {
            weakSelf.favouriteSet = x;
        }else{
            DDFavouriteSet *set = x;
            [weakSelf.favouriteSet.result addObjectsFromArray:set.result];
        }
        [weakSelf.favouriteCollection reloadData];
        weakSelf.currentPage+=1;
        if (weakSelf.favouriteSet.result.count == 0) {
            [weakSelf showNoContentViewWithOriginY:65 image:@"no_jifen" message:@"No Collections!"];
        }else{
            [weakSelf hideNoContentView];
        }
        [weakSelf hideHUD];
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        [weakSelf showMessageHUD:msg delayHide:1.0];
    } completed:^{
        if (block) {
            block();
        }
    }];
}
- (void)cancelCollection:(DDFavouriteItem *)item success:(void(^)())block
{
    [[self.manager deleteCollection:item.goods.goods_id]subscribeNext:^(id x) {
        if (block) {
            block();
        }
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
#pragma mark --- UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    KKLog(@"收藏数量%ld ",self.favouriteSet.result.count);
    return self.favouriteSet.result.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    weak_Self(self);
    static NSString *indentifier = @"FavouriteCell";
    DDFavouriteCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:indentifier forIndexPath:indexPath];
    DDFavouriteItem *item = self.favouriteSet.result[indexPath.row];
    [cell.goodsImage sd_setImageWithURL:[NSURL URLWithString:item.goods.thumbnail] placeholderImage:nil];
    cell.goodsNameLbl.text = item.goods.name;
    cell.priceLbl.text = FormatString(@"$%@", item.goods.price);
    [cell userCollectionBuy:^{
        DDGoodsDetailsViewController *vc = [[DDGoodsDetailsViewController alloc]init];
        vc.goods_id = item.goods.goods_id;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    } cancel:^{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Don you cancel the collection" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Done", nil];
        [alert show];
        [alert click:^(NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                [weakSelf cancelCollection:item success:^{
                    
                    [collectionView performBatchUpdates:^{
                        [weakSelf.favouriteSet.result removeObjectAtIndex:indexPath.row];
                        [collectionView deleteItemsAtIndexPaths:@[indexPath]];
                    } completion:^(BOOL finished){
                        [collectionView reloadData];
                    }];
 
                    if (weakSelf.favouriteSet.result.count == 0) {
                        [weakSelf showNoContentViewWithOriginY:65 image:@"no_jifen" message:@"No Collections!"];
                    }else{
                        [weakSelf hideNoContentView];
                    }
                }];
            }
        }];
    }];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
}
#pragma mark ---- UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat width = (ScreenWidth-3)/2.0;
    CGFloat height = (width-30)+35+30+35+10+15;
    return (CGSize){width,height};
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(2, 1, 1,1);
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 2.f;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 1.f;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.clickBlock) {
        alertView.clickBlock(buttonIndex);
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
